<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户角色
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-switch v-model="query.allflg" class="handle-switch mr40" @change="func_switch_load"
                    placeholder="启用状态" active-value="1" inactive-value="0" active-text="有效角色" inactive-text="全部角色" >
                </el-switch>
                <el-input v-model="query.keyword" placeholder="角色名" class="handle-input mr10"/>
                <el-dropdown split-button type="primary" @click="func_handleSearch" ><i class="el-icon-search mr10"/>搜索
                    <template #dropdown>
                        <el-dropdown-menu >
                        <el-dropdown-item icon="el-icon-edit" @click="func_handleAddBut">新建</el-dropdown-item>
                        <el-divider />
                        <el-dropdown-item icon="el-icon-refresh-right" @click="func_handleRecyclingBut">恢复</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-delete" @click="func_handleDelBut">删除</el-dropdown-item>
                        <el-divider />
                        <el-dropdown-item icon="el-icon-circle-check" @click="func_handleActiveBut">启用</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-circle-close" @click="func_handleUnActiveBut">停用</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <el-table v-loading="isLoading" :data="role_table_data" border class="table" ref="multipleTable"
            element-loading-background = "rgba(255, 255, 255, .5)" element-loading-text = "加载中，请稍后..." element-loading-spinner = "el-icon-loading"
            @selection-change="(selections)=>{func_handleSelectionChange(selections,'true')}"
            @select-all="(selections)=>{func_handleSelectionAll(selections,'true')}"
            header-cell-class-name="table-header" default-expand-all >>
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column prop="id" label="ID" width="55" align="center"/>
                <el-table-column prop="sid" label="识别码" v-if="false" align="center"/>
                <el-table-column prop="name" label="名称" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-s-unfold" @click="func_handleDrawerOpen(scope.$index, scope.row)">{{scope.row.name}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="strIsAdministration" v-if="true" label="角色区分" align="center"/>
                <el-table-column v-if="false">
                    <template #default="scope"> {{scope.row.checked}} {{scope.row.status}}</template>
                </el-table-column>
                <el-table-column label="可见" align="center">
                    <template #default="scope">
                        <p v-if="scope.row.checked"><el-tag type="info" size="small" effect="dark">{{scope.row.strChecked}}</el-tag></p>
                        <p v-if="!scope.row.checked"><el-tag type="danger" size="small" effect="dark">{{scope.row.strChecked}}</el-tag></p>
                    </template>
                </el-table-column>
                <el-table-column label="有效" align="center">
                    <template #default="scope">
                        <p v-if="scope.row.status === 1"><el-tag type="info" size="small" effect="dark">{{scope.row.strStatus}}</el-tag></p>
                        <p v-if="scope.row.status === 0"><el-tag type="danger" size="small" effect="dark">{{scope.row.strStatus}}</el-tag></p>
                    </template>
                </el-table-column>
                <el-table-column label="数据状态" align="center">
                    <template #default="scope">
                        <p v-if="scope.row.isDel"><el-tag size="small" type="danger" effect="dark">已删除</el-tag></p>
                        <p v-if="!scope.row.isDel"><el-tag size="small" type="success" effect="dark">正常</el-tag></p>
                    </template>
                </el-table-column>
                <el-table-column prop="strCreateTime" label="创建时间" align="center"/>
                <el-table-column label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-edit" @click="func_handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="func_handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @size-change="func_handle_size_change" @current-change="func_handle_page_change"
                background layout="total, sizes, prev, pager, next," 
                        :current-page="query.pageNum"
                        :page-sizes=[10,50,100]
                        :page-size="query.pageSize"
                        :total="query.total" >
                </el-pagination>
            </div>
        </div>
        <!-- ---------------------------------------------------------------------------------------------------------------------- -->
        <!-- 编辑弹出框 ------------------------------------------------------------------------------------------------------------ -->
        <el-dialog v-model="view_edit_visible" width="55%" :close-on-click-modal="false">
            <div class="handle-box">
                <span><h3>{{role_form_headTitle}}</h3></span>
            </div>
            <el-card class="box-card">
            <el-form label-width="formLabelWidth">
               <el-form-item label="用户名" >
                   <el-input v-model="role_form.name" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="可见状态" >
                    <el-select v-model="role_form.checked" placeholder="是否可见">
                    <el-option label="请选择" value=""></el-option>
                    <el-option v-for="item in check_Opts" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色状态" >
                    <el-select v-model="role_form.status" placeholder="是否启用">
                    <el-option label="请选择" value=""></el-option>
                    <el-option v-for="item in status_Opts" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" >
                    <el-select v-model="role_form.sort" placeholder="角色排序">
                        <el-option label="1" value="1"></el-option>
                        <el-option label="2" value="2"></el-option>
                        <el-option label="3" value="3"></el-option>
                        <el-option label="4" value="4"></el-option>
                        <el-option label="5" value="5"></el-option>
                        <el-option label="6" value="6"></el-option>
                        <el-option label="7" value="7"></el-option>
                        <el-option label="8" value="8"></el-option>
                        <el-option label="9" value="9"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="描述" >
                    <el-input type="textarea" placeholder="请输入内容" v-model="role_form.description" maxlength="30" show-word-limit >
                    </el-input>
                </el-form-item>
            </el-form>
            </el-card>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="view_edit_visible = false">取 消</el-button>
                    <el-button type="primary" @click="func_dialog_saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- ---------------------------------------------------------------------------------------------------------------------- -->
        <!-- 详细抽屉 -------------------------------------------------------------------------------------------------------------- -->
        <el-drawer title="详细信息" v-model="view_role_drawer" direction="rtl" size="55%">
            <el-tabs v-model="view_activeName" type="border-card" @tab-click="func_drawer_tabsBut" style="height:98%;overflow-y:auto;overflow-x:hidden">
                <el-tab-pane label="角色说明" name="role" :key="'role'">
                    <el-card class="box-card">
                    <el-descriptions title="明细信息" direction="vertical" :column="3" border>
                    <el-descriptions-item label="ID" :span="3">{{role_drawer_form.id}}</el-descriptions-item>
                    <el-descriptions-item label="名称" :span="3">{{role_drawer_form.name}}</el-descriptions-item>
                    <el-descriptions-item label="识别码" :span="3">{{role_drawer_form.sid}}</el-descriptions-item>
                    <el-descriptions-item label="可见状态">
                        <el-tag size="small">{{role_drawer_form.strChecked}}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag size="small">{{role_drawer_form.strStatus}}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="角色区分">
                        <el-tag size="small">{{role_drawer_form.strIsAdministration}}</el-tag>
                    </el-descriptions-item>
                    </el-descriptions></el-card>
                    <el-divider content-position="right">我是分割线</el-divider>
                    <el-card class="box-card">
                    <el-descriptions title="系统信息" direction="vertical" :column="3" border>
                        <el-descriptions-item label="创建时间" :span=3>{{role_drawer_form.strCreateTime}}</el-descriptions-item>
                        <el-descriptions-item label="创建人" :span=3>{{role_drawer_form.strCreateTime}}</el-descriptions-item>
                        <el-descriptions-item label="最后一次编辑时间" :span=3>{{role_drawer_form.strCreateTime}}</el-descriptions-item>
                    </el-descriptions></el-card>
                </el-tab-pane>
                <!-- -------------------------------------------------------------------------------------------------------------- -->
                <!-- #2. 用户 ----------------------------------------------------------------------------------------------------- -->                
                <el-tab-pane label="关联用户" name="member" :key="'member'">
                    <el-card class="box-card">
                    <el-table :data="role_member_table_data" border class="table" :max-height="750" fit highlight-current-row header-cell-class-name="table-header">
                        <el-table-column prop="uid" label="ID" width="55" align="center"/>
                        <el-table-column label="识别码" v-if="false">
                            <template #default="scope">
                            {{scope.row.id}}, {{scope.row.sid}},{{scope.row.usid}},{{scope.row.uisAdmin}},{{scope.row.ustatus}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="username" label="用户名"/>
                        <el-table-column prop="uphone" label="手机号"/>
                    </el-table>
                    <div class="pagination">
                        <el-pagination  @size-change="func_drawer_table_handle_pagesize_change" @current-change="func_drawer_table_handle_page_change"
                        background layout="total, sizes, prev, pager, next,"
                        :current-page="role_member_query.pageNum"
                        :page-sizes=[10,50,100] 
                        :page-size="role_member_query.pageSize"
                        :total="role_member_query.total" ></el-pagination>
                    </div>
                    </el-card>
                </el-tab-pane>
                <!-- -------------------------------------------------------------------------------------------------------------- -->
                <!-- #3. 角色 ----------------------------------------------------------------------------------------------------- -->
                <!-- <el-tab-pane label="关联资源" name="permission" :key="'permission'">
                    <el-card class="box-card"></el-card>
                </el-tab-pane> -->
                <!--  ------------------------------------------------------------------------------------------------------------- -->
            </el-tabs>
        </el-drawer>

   </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchMemberData, fetchRoleData, editRole, batchDelRoler, batchRecRoler, batchActRoler,
        fetchRoleMembers, editRoleMemberConn, } from "../../api/uc";

export default {
    name: "roletable",
    setup() {
        let SUCCMESS_DIALOG_MESSAGE = "操作成功";
        let ERROR_CHOOSE_REC_ROLE_EMPTY = "请选择一个操作角色";
        // 表单loading: true,
        const isLoading = ref(true);
        // 表单输入框前长度
        const formLabelWidth = ref("170px");
        // 角色查询条件
        const query = reactive({
            keyword: "",
            allflg: 0,
            pageNum: 1,
            pageSize: 10,
            total: 0,
        });
        // 角色数据表
        const role_table_data = ref([{
            id: 0,
            sid: '',
            name: '',
            status: 0,
            checked: 0,
            strCreateTime: '',
            strStatus: '',
            strIsAdministration: ''
        }]);
        // 公共 数据表多选临时存储
        let multipleTable = ref([]);
        let multipleSelectData =reactive([]);
        /**
         * @name 公共 列表内选择数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionChange = (selections,param) => {
            multipleSelectData =selections;
        };
        /**
         * @name 公共 列表内全选数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionAll = (selections,param) => {
            multipleSelectData = selections;
        };
        let role_form_headTitle = ref("");
        let role_form = reactive({
            id: 0,
            sid: '',
            name: '',
            status: 0,
            checked: 0,
            description: '',
            strCreateTime: '',
            strStatus: '',
            strIsAdministration: '',
            adminCount: 0,
            mngflg: 0,
            sort: 1,
            roleMemo1: '',
            roleMemo2: 0,
        });
        let role_drawer_form = reactive({
            id: 0,
            sid: '',
            name: '',
            checked: 0,
            status: 0,
            strCreateTime: '',
            strStatus: '',
            strIsAdministration: ''
        });
        /**
         * @name 获取主表格数据
         */
        const func_getData = () => {
            role_table_data.value= [];
            var t= setTimeout(function() {
                fetchRoleData(query).then((res) => {
                    role_table_data.value = res.data.data.list;
                    query.total = res.data.data.total;
                    isLoading.value = false;
                }).catch(() => { isLoading.value = false;});
            },1000);
        };
        func_getData();
        /**
         * @name 回收ID的数据
         */
        const func_rec_data = (_data) => {
            batchRecRoler(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 删除ID的数据
         */
        const func_del_data = (_data) => {
            batchDelRoler(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 激活关闭ID的数据
         */
        const func_act_data = (_data) => {
            batchActRoler(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 查询操作
         */
        const func_handleSearch = () => {
            isLoading.value = true;
            query.pageNum = 1;
            func_getData();
        };
        /**
         * @name 开关切换查询
         */
        const func_switch_load =() => {
            isLoading.value = true;
            query.pageNum = 1;
            func_getData();
        };
        /**
         * @name 分页导航
         */
        const func_handle_page_change = (val) => {
            query.pageNum = val;
            func_getData();
        };
        /**
         * @name 分页数量查询
         */
        const func_handle_size_change = (val) => {
            query.pageSize = val;
            func_getData();
        };
        /**
         * @name 添加操作
         */
        const func_handleAddBut = () => {
            role_form_headTitle.value = "添加系统角色";
            view_edit_visible.value = true;
            Object.keys(role_form).forEach((item) => {
                role_form[item] = '';
            });
            return;
        }
        /**
         * 标签内方法
         * @name 角色批量恢复方法
         * @description 主按钮下拉的批量恢复操作
         */
        const func_handleRecyclingBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_REC_ROLE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_rec_data(_v);
        };
        /**
         * 标签内方法
         * @name 角色批量删除方法
         * @description 主按钮下拉的批量删除操作
         */
        const func_handleDelBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_REC_ROLE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_del_data(_v);
        };
        /**
         * 标签内方法
         * @name 角色批量激活方法
         * @description 主按钮下拉的批量删除操作
         */
        const func_handleActiveBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_REC_ROLE_EMPTY);
                return;
            }
            let _ids = multipleSelectData.map((item) => item.id);
            let _v = {
                ids: _ids, flg: 1
            };
            func_act_data(_v);
        };
        /**
         * 标签内方法
         * @name 角色批量停用方法
         * @description 主按钮下拉的批量删除操作
         */
        const func_handleUnActiveBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_REC_ROLE_EMPTY);
                return;
            }
            let _ids = multipleSelectData.map((item) => item.id);
            let _v = {
                ids: _ids, flg: 0
            };
            func_act_data(_v);
        };
        const check_Opts = ref([{
            key :0,
            label :'不可见',
            value :0,
        },{
            key :1,
            label :'可见',
            value :1,
        }]);
        const status_Opts = ref([{
            key :1,
            label :'启用',
            value :1,
        },
        {
            key :0,
            label :'停用',
            value :0,
        }]);
        /**
         * @name 表格行内编辑操作
         */
        let idx = -1;
        const func_handleEdit = (index, row) => {
            idx = index;
            role_form_headTitle.value = "编辑系统角色";
            Object.keys(role_form).forEach((item) => {
                if(item === "checked"){
                    if(row[item]){
                        role_form[item] = 1
                    }else{
                        role_form[item] = 0
                    }
                } else
                if(item === 'status'){
                    if(row[item] === 1){
                        role_form[item] = 1
                    }else{
                        role_form[item] = 0
                    }
                }else{
                    role_form[item] = row[item];
                }
            });
            view_edit_visible.value = true;
        };
        /**
         * @name 表格行内删除操作
         */
        const func_handleDelete = (index, row) => {
            // 二次确认删除
            ElMessageBox.confirm("确定要删除吗？", "提示", {type: "warning",}).then(() => {
                let _ids = [row['id']];
                batchDelRoler(_ids).then((res)=>{
                    if(res.data.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                        isLoading.value = true;
                        func_getData(); // 刷新数据
                    }
                });
            }).catch(() => {});
        };
        /**
         * ----------------------------------------------------抽屉内方法-------------------------------------------------*/
        // 抽屉展示区分
        const view_role_drawer = ref(false);
        // 抽屉内标签页区分
        const view_activeName = ref();
        const role_member_query = reactive({
            sid: "",
            pageNum: 1,
            pageSize: 10,
            total: 0,
        });
        // 抽屉内角色用户列表
        const role_member_table_data = ref([{
            id: 0,
            sid: '',
            usid: '',
            username: '',
            uphone: '',
            uisAdmin:0,
            ustatus: ''
        }]);
        /**
         * @name 打开弹出层
         */
        const func_handleDrawerOpen = (index, row) => {
            Object.keys(row).forEach((item) => {
                role_drawer_form[item] = row[item];
            });
            // 初始化抽屉内标签
            view_activeName.value = "role";
            // 设定抽屉显示
            view_role_drawer.value = true;
        };
        /**
         * Drawer内列表处理
         * @name 标签切换方法
         */
        const func_drawer_tabsBut = (tab,event) => {
            // 角色内标签判定
            if(tab.index == 1 ){
                func_drawer_table_handleRoleMember(role_drawer_form.sid);
            }
        };
        /**
         * 抽屉效果关闭的提示方法
         */
        const func_handleDrawerClose = (done) =>{
            this.$confirm('确认关闭？').then(_ => {
                done();
            }).catch(_ => {});
        };
        /**
         * Drawer内列表处理
         * @name 查询角色下所有用户
         */
        const func_drawer_table_handleRoleMember = (roleSid) =>{
            role_member_query.sid = roleSid;
            role_member_query.pageNum = 1;
            fetchRoleMembers(role_member_query).then((res) => {
                role_member_query.total = res.data.data.total;
                role_member_table_data.value = res.data.data.list;
            }).catch(_ => {});
        };
        /**
         * ----------------------------------------------------对话框方法-------------------------------------------------*/
        // 表格编辑时弹窗和保存
		let view_edit_visible = ref(false);
        const func_dialog_saveEdit = () => {
            editRole(role_form).then((res)=>{
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    view_edit_visible.value = false;
                    ElMessage.success(`修改第 ${idx + 1} 行成功`);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            })
        };
        // 分页导航
        const func_drawer_table_handle_pagesize_change = (val) => {
            query.pageSize = val;
            func_getData();
        };
        const func_drawer_table_handle_page_change = (val) => {
            query.pageIndex = val;
            func_getData();
        };
        /**
         * ----------------------------------------------------初始化页面对象---------------------------------------------*/
        return {
            isLoading, query, role_member_query, formLabelWidth,
            role_form_headTitle,
            multipleTable, multipleSelectData,
            func_handleSelectionAll,
            func_handleSelectionChange,
            view_edit_visible, view_role_drawer, view_activeName,
            role_table_data, role_member_table_data, role_form, role_drawer_form, check_Opts, status_Opts,
            func_getData, func_rec_data, func_del_data, func_act_data, func_handleSearch, func_switch_load, func_handle_page_change, func_handle_size_change,
            func_handleAddBut, func_handleRecyclingBut, func_handleDelBut, func_handleUnActiveBut, func_handleActiveBut, func_drawer_tabsBut, func_handleDrawerClose,
            func_handleEdit, func_handleDelete, func_dialog_saveEdit,
            func_handleDrawerOpen, func_drawer_table_handleRoleMember, func_drawer_table_handle_pagesize_change, func_drawer_table_handle_page_change
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}
.handle-switch {
    width: 180px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-input {
    width: 350px;
}
.box-card {
    width: 99%;
}
.box-card.button {
    padding: 0;
    float: right;
}
.submit-button {
    padding: 0;
    float:right;
}

</style>